<script setup>
import { ref, reactive, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import {login, sendCode, getUserInfo} from '@/api/use' // 验证码相关API

// 表单数据
const form = reactive({
  phone: '', // 手机号或账号
  code: ''  // 验证码
})

onMounted(()=>{
  if(localStorage.getItem('token')){
    router.push('/home')
  }
})

// 表单验证规则
const rules = {
  phone: [
    { required: true, message: '请输入手机号', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号', trigger: 'blur' }
  ],
  code: [
    { required: true, message: '请输入验证码', trigger: 'blur' },
    { len: 6, message: '验证码长度为6位', trigger: 'blur' }
  ]
}

// 状态管理
const loginForm = ref(null)
const loading = ref(false)
const countDown = ref(0)
const router = useRouter()

// 获取验证码
const getCaptcha = async () => {
  // 验证手机号
  const valid = await loginForm.value.validateField('phone');
  console.log(11111111,valid);
  if (!valid) return
  try {
    // 调用发送验证码API
    const res = await sendCode({phone: form.phone});
    console.log(res);
    ElMessage.success('验证码已发送，请注意查收')
    
    // 开始倒计时
    countDown.value = 60
    const timer = setInterval(() => {
      countDown.value--
      if (countDown.value <= 0) {
        clearInterval(timer)
      }
    }, 1000)
  } catch (error) {
    ElMessage.error(error.message || '发送验证码失败')
  }
}

// 处理登录
const handleLogin = async () => {
  // 表单验证
  const valid = await loginForm.value.validate()
  if (!valid) return

  try {
    loading.value = true
    // 调用验证码登录API
    const response = await login(form)
    console.log(response);
    // 登录成功处理
    ElMessage.success('登录成功')
    console.log(response.data);
    // 存储token等操作
    localStorage.setItem('token',response.data.token);
    localStorage.setItem('userId',response.data.userId);
    setTimeout(async ()=>{
      const res = await getUserInfo();
      if(res.code === 200){
        localStorage.setItem('userInfo',JSON.stringify(res.data));
      }
      router.push('/home')
    },1000)
    // 跳转到首页
    
  } catch (error) {
    ElMessage.error(error.message || '登录失败，请检查验证码是否正确')
  } finally {
    loading.value = false
  }
}
</script>

<template>
  <div class="main">
    <div class="mainTop" @click="tabPage">
      <img src="@/assets/img_text.png" />
    </div>
    <div class="login-container">
    <div class="login-box">
      <div class="title">用户登录</div>
      <el-form 
        ref="loginForm" 
        :model="form" 
        :rules="rules" 
        class="login-form"
      >
        <!-- 手机号/账号输入框 -->
        <el-form-item prop="phone">
          <el-input 
            v-model="form.phone" 
            placeholder="请输入手机号" 
            prefix-icon="Phone"
            maxlength="11"
          ></el-input>
        </el-form-item>
        <!-- 验证码输入框和获取按钮 -->
        <el-form-item prop="code">
          <el-input 
            v-model="form.code" 
            placeholder="请输入验证码" 
            prefix-icon="Key"
            maxlength="6"
          ></el-input>
          <el-button 
            type="text" 
            class="get-captcha-btn"
            @click="getCaptcha"
            :disabled="countDown > 0">
            {{ countDown > 0 ? `${countDown}s后重新获取` : '获取验证码' }}
          </el-button>
        </el-form-item>
        
        <!-- 登录按钮 -->
        <el-form-item>
          <el-button 
            type="primary" 
            class="login-btn"
            @click="handleLogin"
            :loading="loading"
          >
            登录
          </el-button>
        </el-form-item>
      </el-form>
    </div>
  </div>
  </div>
</template>

<style scoped lang="scss">
.main {
  height: 100vh;
  padding: 0px 24px;
  background: url("@/assets/bg.png");
  background-size: 100% 100%;
  background-repeat: no-repeat;
  .mainTop {
    width: 100%;
    height: 97px;
    display: block;
    padding-top: 14px;
    position: relative;
    background: url("@/assets/top.png");
    background-size: 100% 100%;
    background-repeat: no-repeat;
    background-position: center;
    img {
      width: 504px;
      height: 53px;
    }
  }
  
}
.login-container {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 80vh;
}

.login-box {
  width: 350px;
  padding: 30px;
  background-color: #fff;
  border-radius: 8px;
}

.login-box .title {
  font-size: 22px;
  text-align: center;
  margin-bottom: 20px;
  color: #333;
  font-weight: bold;
}

.login-form {
  .el-form-item {
    position: relative;
    margin-bottom: 20px;
  }
  
  .get-captcha-btn {
    position: absolute;
    right: 10px;
    top: 50%;
    transform: translateY(-50%);
    padding: 0 10px;
    color: #409eff;
  }
}

.login-btn {
  width: 100%;
  padding: 12px 0;
  font-size: 16px;
}
</style>
